package com.biodiv.community.client;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;

/**
 * @author tianquan
 */
@Service
public class GeoIPClient {

    @Autowired(required = false)
    private DatabaseReader dbReader;

    /**
     * 国家
     */
    public String getCountry(String ip) {
        try {
            CountryResponse response = dbReader.country(InetAddress.getByName(ip));
            return response.getCountry().getNames().get("zh-CN");
        } catch (Exception e) {
            return "Unknown";
        }
    }

    /**
     * 城市
     */
    public String getCity(String ip) {
        try {
            CityResponse response = dbReader.city(InetAddress.getByName(ip));
            return response.getCity().getNames().get("zh-CN");
        } catch (Exception e) {
            return "Unknown";
        }
    }

    /**
     * 省
     */
    public String getProvince(String ip) {
        try {
            CityResponse response = dbReader.city(InetAddress.getByName(ip));
            return response.getMostSpecificSubdivision().getNames().get("zh-CN");
        } catch (Exception e) {
            return "Unknown";
        }
    }

    /**
     * 检查 IP 是否是美国的
     */
    public boolean isFromUnitedStates(String ip) {
        try {
            CountryResponse response = dbReader.country(InetAddress.getByName(ip));
            // 判断国家是否是 United States
            return "United States".equalsIgnoreCase(response.getCountry().getName());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}